package cn.caplike.demo.repository.javaagent.app;

import com.sun.tools.attach.*;

import java.io.IOException;
import java.lang.annotation.Target;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.util.List;

public class Main {

    static String AGENT_JAR_PATH = "/Users/like/IdeaProjects/demo/demo-repository/byte-code/java-agent/java-agent-agentmain/target/java-agent-agentmain-1.0.0-SNAPSHOT.jar";

    public static void main(String[] args) throws AgentLoadException, IOException, AgentInitializationException, AttachNotSupportedException, InterruptedException {
        // listJar();

        // getProcessId();
        // final Aaaaa aaaaa = new Aaaaa();

        for (final VirtualMachineDescriptor descriptor : VirtualMachine.list()) {
            final String displayName = descriptor.displayName();
            if (displayName.endsWith("cn.caplike.demo.repository.javaagent.app.Main")) {
                final String id = descriptor.id();
                final VirtualMachine machine = VirtualMachine.attach(id);
                machine.loadAgent(AGENT_JAR_PATH);
                machine.detach();
            }
        }
    }

    private static void getProcessId() {
        final RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
        final String processName = runtimeMXBean.getName();
        long pid = Long.parseLong(processName.split("@")[0]);
        System.out.println("Process ID: " + pid);
    }

    private static void listJar() {
        final String classpath = System.getProperty("java.class.path");
        final String[] jarPaths = classpath.split(System.getProperty("path.separator"));
        for (final String jarPath : jarPaths) {
            if (jarPath.endsWith(".jar")) {
                System.out.println(jarPath);
            }
        }
    }
}
